// 获取全局唯一录音管理器
const recorderManager = wx.getRecorderManager();

// 监听录音开始事件
recorderManager.onStart(() => {
	console.log('录音开始');
});

// 监听录音结束事件
recorderManager.onStop((res) => {
	console.log('录音结束', res);

	const {
		tempFilePath
	} = res;
	wx.showToast({
		title: '录音结束',
		icon: 'success',
		duration: 2000
	});

	// 创建音频上下文对象
	const audioContext = wx.createInnerAudioContext();
	audioContext.src = tempFilePath;

	// 开始播放录音
	audioContext.play();

	// 创建音频分析器
	const audioContext = wx.createInnerAudioContext();
	audioContext.src = tempFilePath;
	audioContext.autoplay = true;
	audioContext.onPlay(() => {
		console.log('开始播放录音');
	});

	const analyser = wx.createAnalyser(); // 创建音频分析器
	analyser.fftSize = 2048; // 设置 FFT 大小
	const bufferLength = analyser.frequencyBinCount;
	const dataArray = new Float32Array(bufferLength);

	// 连接音频源与分析器
	audioContext.connect(analyser);

	// 定时获取音频数据并处理
	setInterval(() => {
		analyser.getFloatTimeDomainData(dataArray); // 获取实时音频数据
		const pitch = estimatePitch(dataArray, audioContext.sampleRate); // 估算音高
		console.log('当前音调:', pitch.toFixed(2) + ' Hz');

		// 显示当前音符
		const noteName = getNoteName(pitch);
		console.log('当前音符:', noteName);
		// 这里可以根据需要处理估计的音高
	}, 100); // 每隔100毫秒进行一次音高估计

	// 音高估算函数（示例：基于自相关函数的方法）
	function estimatePitch(dataArray, sampleRate) {
		const correlation = new Array(dataArray.length).fill(0);

		// 自相关函数
		for (let lag = 0; lag < dataArray.length; lag++) {
			for (let i = 0; i < dataArray.length - lag; i++) {
				correlation[lag] += dataArray[i] * dataArray[i + lag];
			}
		}

		// 找到自相关函数的峰值（即最大值）
		let peakIndex = 0;
		for (let i = 1; i < correlation.length; i++) {
			if (correlation[i] > correlation[peakIndex]) {
				peakIndex = i;
			}
		}

		// 计算估计的音高（Pitch）
		const pitch = sampleRate / peakIndex;
		return pitch;
	}

	// 根据音高获取音符名
	function getNoteName(pitch) {
		const notes = [{
				name: 'C',
				frequency: 261.63
			},
			{
				name: 'D',
				frequency: 293.66
			},
			{
				name: 'E',
				frequency: 329.63
			},
			{
				name: 'F',
				frequency: 349.23
			},
			{
				name: 'G',
				frequency: 392.00
			},
			{
				name: 'A',
				frequency: 440.00
			},
			{
				name: 'B',
				frequency: 493.88
			}
		];

		// 比较 pitch 和标准音符频率，选择最接近的音符
		let closestNote = '';
		let minDistance = Infinity;

		for (let i = 0; i < notes.length; i++) {
			const distance = Math.abs(pitch - notes[i].frequency);
			if (distance < minDistance) {
				minDistance = distance;
				closestNote = notes[i].name;
			}
		}

		return closestNote;
	}
});

// 开始录音函数
export function startRecording() {
	recorderManager.start({
		duration: 600000,
		sampleRate: 44100,
		numberOfChannels: 1,
		encodeBitRate: 192000,
		format: 'PCM',
		frameSize: 10

	});
}

// 停止录音函数
function stopRecording() {
	recorderManager.stop();
}